import { useDeleteArticle, useGetAllArticles } from '@/services/article';
import {
  StarOutlined,
  LikeOutlined,
  MessageOutlined,
  TagsOutlined,
  EditOutlined,
  DeleteOutlined,
  ExclamationCircleFilled,
  EyeOutlined,
  FieldTimeOutlined,
} from '@ant-design/icons';
import { ProList } from '@ant-design/pro-components';
import { history, useModel } from '@umijs/max';
import { Button, Modal, Select, Space, Tag } from 'antd';
import React, { useMemo, useState } from 'react';
import { CoverImg, OverflowHiddenText } from './style';

export const IconText = ({ icon, text }: { icon: any; text: string }) => (
  <span>
    {React.createElement(icon, { style: { marginInlineEnd: 8 } })}
    {text}
  </span>
);

const { confirm } = Modal;

const MyArticles: React.FC = () => {
  const { initialState } = useModel('@@initialState');
  const [hoverId, setHoverId] = useState<number>();
  const { data: source } = useGetAllArticles(initialState?.id ?? -1);
  const { mutateAsync: deleteArticle } = useDeleteArticle();
  const [activeKey, setActiveKey] = useState<number>(-1);
  const showConfirm = (article: API.IArticles) => {
    confirm({
      title: `你确定要删除"${article.title}"这篇文章吗？`,
      icon: <ExclamationCircleFilled />,
      content: `${article.introduction}`,
      onOk() {
        if (article.id) deleteArticle(article.id);
      },
    });
  };

  const dataSource = useMemo(() => {
    return (
      source?.data &&
      source.data
        .filter((x) =>
          activeKey === -1
            ? true
            : parseInt(x.isQuestion as string) === activeKey,
        )
        .map((item: API.IArticles) => ({
          ...item,
          title: <OverflowHiddenText row={1}>{item.title}</OverflowHiddenText>,
          subTitle:
            item.id === hoverId ? (
              <Space>
                <Button
                  type="primary"
                  size="small"
                  onClick={() => {
                    history.push(`/dashboard/edit?id=${item.id}`);
                  }}
                  icon={<EditOutlined />}
                ></Button>
                <Button
                  type="primary"
                  size="small"
                  icon={<DeleteOutlined />}
                  danger
                  onClick={() => showConfirm(item)}
                ></Button>
              </Space>
            ) : (
              ''
            ),
        }))
    );
  }, [source, hoverId, activeKey]);

  return (
    <>
      <ProList<any>
        toolBarRender={() => {
          return [
            <Select
              key="articleType"
              defaultValue={activeKey}
              style={{ width: 120 }}
              onChange={(e) => setActiveKey(e)}
              options={[
                { value: -1, label: '全部' },
                { value: 0, label: '普通' },
                { value: 1, label: '问题' },
              ]}
            />,
            <Button
              key="add"
              type="primary"
              onClick={() => history.push('/dashboard/write')}
            >
              去创作
            </Button>,
          ];
        }}
        onRow={(record: any) => {
          return {
            onDoubleClick: () => {
              history.push(`/article?id=${record.id}`);
            },
            onMouseEnter: () => setHoverId(record.id),
          };
        }}
        itemLayout="vertical"
        rowKey="id"
        headerTitle="我的创作历史"
        tooltip="尊重知识产权，从我做起"
        dataSource={dataSource}
        metas={{
          title: {},
          subTitle: {},
          description: {
            render: (_, record) => (
              <Space>
                <TagsOutlined />
                {record.tags &&
                  record.tags.split('/').map((tag: string, i: number) => (
                    <Tag color="#5BD8A6" key={i}>
                      {tag}
                    </Tag>
                  ))}
              </Space>
            ),
          },
          extra: {
            render: (_: any, record: { avatar: string | undefined }) => {
              return record.avatar ? (
                <CoverImg src={record.avatar ?? ''}></CoverImg>
              ) : (
                ''
              );
            },
          },
          content: {
            render: (_, record) => {
              return (
                <OverflowHiddenText>{record.introduction}</OverflowHiddenText>
              );
            },
          },
          actions: {
            render: (_, record) => [
              <IconText
                icon={FieldTimeOutlined}
                text={record.time}
                key="time"
              />,
              <span style={{ width: 20 }} key="space"></span>,
              <IconText
                icon={EyeOutlined}
                text={record.lookNum ?? 0}
                key="list-vertical-eye"
              />,
              <IconText
                icon={StarOutlined}
                text={record.starNum ?? 0}
                key="list-vertical-star"
              />,
              <IconText
                icon={LikeOutlined}
                text={record.likeNum ?? 0}
                key="list-vertical-like"
              />,
              <IconText
                icon={MessageOutlined}
                text={record.commentNum ?? 0}
                key="list-vertical-message"
              />,
            ],
          },
        }}
      />
    </>
  );
};

export default MyArticles;
